package www.dianbaozu.com.ui.chat.findFriend

import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.luck.picture.lib.decoration.WrapContentLinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.FlowPreview
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentFindFriendsMessagesBinding
import www.dianbaozu.com.ui.chat.findFriend.adapter.FindFriendsAdapter
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.extension.banEnterKey
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter

/**
 * @author WEN
 * @Description:查找好友和私信
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class FindFriendsMessagesFragment : BaseLoadingFragment<FragmentFindFriendsMessagesBinding>(),
    View.OnClickListener {

    private val findFriendsMessagesViewModel: FindFriendsMessagesViewModel by viewModels()

    private val adapter: FindFriendsAdapter by lazy {
        FindFriendsAdapter(
            dataBinding.rvListFriend,
            mutableListOf()
        )
    }

    override val viewModel: BaseViewModel
        get() = findFriendsMessagesViewModel

    override fun isEnableLoadingHelper(): Boolean = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter =
        TitleBarUniversalAdapter(requireActivity(), "查找好友和私信", action = ::titleAction)

    override fun getLayoutId(): Int = R.layout.fragment_find_friends_messages

    override fun lazyInitView() {
        dataBinding.apply {
            listener = this@FindFriendsMessagesFragment

            rvListFriend.adapter = adapter
            rvListFriend.layoutManager = WrapContentLinearLayoutManager(requireActivity())
            etSearch.addTextChangedListener {
                adapter.clearData()
                adapter.removeAllFooterView()
                adapter.removeAllHeaderView()
                searchFriend(it.toString().trim())
                searchAllMessage(it.toString().trim())
            }
            etSearch.banEnterKey()
        }
    }

    override fun onClick(v: View) {
        findNavController().navigateUp()
    }

    @FlowPreview
    private fun searchFriend(keyword: String) {
        findFriendsMessagesViewModel.searchFriend(keyword,
            success = {
                if (it.data.isNotEmpty()) {
                    adapter.addData("好友")
                }
                adapter.addData(it.data)
            })
    }

    @FlowPreview
    private fun searchAllMessage(keyword: String) {
        findFriendsMessagesViewModel.searchAllMessage(keyword,
            success = {
                if (it.data.isNotEmpty()) {
                    adapter.addData("私聊记录")
                }
                adapter.addData(it.data)
            })
    }

}



